#!/bin/bash

# ENPlatform Assistant MySQL 管理脚本
# 用于管理本地Docker部署的MySQL服务

set -e

# 配置变量
CONTAINER_NAME="enplatform-mysql"
MYSQL_ROOT_PASSWORD="enplatform123"
MYSQL_DATABASE="enplatform_assistant"
MYSQL_USER="enplatform"
MYSQL_PASSWORD="enplatform123"
BACKUP_DIR="./backups"
COMPOSE_FILE="docker-compose.yml"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Docker是否运行
check_docker() {
    if ! docker info >/dev/null 2>&1; then
        log_error "Docker is not running. Please start Docker first."
        exit 1
    fi
}

# 检测和优化架构
setup_architecture() {
    log_info "检测系统架构并优化配置..."

    if [[ -f "scripts/architecture-setup.sh" ]]; then
        bash scripts/architecture-setup.sh
    else
        log_warning "架构设置脚本不存在，使用默认配置"
    fi
}

# 检查docker-compose是否存在
check_compose() {
    if ! command -v docker-compose &> /dev/null; then
        log_error "docker-compose is not installed. Please install docker-compose first."
        exit 1
    fi
}

# 创建必要的目录
create_directories() {
    log_info "Creating necessary directories..."
    mkdir -p volumes/data volumes/logs volumes/conf init $BACKUP_DIR
    log_success "Directories created successfully"
}

# 启动MySQL服务
start_mysql() {
    log_info "Starting MySQL service..."
    check_docker
    check_compose
    create_directories
    
    if docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
        log_warning "MySQL container is already running"
        return 0
    fi
    
    docker-compose -f $COMPOSE_FILE up -d mysql
    
    log_info "Waiting for MySQL to be ready..."
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if docker exec $CONTAINER_NAME mysqladmin ping -h localhost -u root -p$MYSQL_ROOT_PASSWORD --silent >/dev/null 2>&1; then
            log_success "MySQL is ready!"
            break
        fi
        
        if [ $attempt -eq $max_attempts ]; then
            log_error "MySQL failed to start within expected time"
            exit 1
        fi
        
        log_info "Attempt $attempt/$max_attempts - waiting for MySQL..."
        sleep 5
        ((attempt++))
    done
    
    log_success "MySQL service started successfully"
}

# 停止MySQL服务
stop_mysql() {
    log_info "Stopping MySQL service..."
    docker-compose -f $COMPOSE_FILE down
    log_success "MySQL service stopped successfully"
}

# 重启MySQL服务
restart_mysql() {
    log_info "Restarting MySQL service..."
    stop_mysql
    sleep 2
    start_mysql
}

# 查看服务状态
status_mysql() {
    log_info "Checking MySQL service status..."
    
    if docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
        log_success "MySQL container is running"
        docker ps -f name=$CONTAINER_NAME --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
        
        # 检查MySQL服务是否响应
        if docker exec $CONTAINER_NAME mysqladmin ping -h localhost -u root -p$MYSQL_ROOT_PASSWORD --silent >/dev/null 2>&1; then
            log_success "MySQL service is healthy"
        else
            log_warning "MySQL container is running but service is not responding"
        fi
    else
        log_warning "MySQL container is not running"
    fi
}

# 查看日志
logs_mysql() {
    log_info "Showing MySQL logs..."
    docker-compose -f $COMPOSE_FILE logs -f mysql
}

# 连接到MySQL
connect_mysql() {
    log_info "Connecting to MySQL..."
    
    if ! docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
        log_error "MySQL container is not running. Please start it first."
        exit 1
    fi
    
    docker exec -it $CONTAINER_NAME mysql -u root -p$MYSQL_ROOT_PASSWORD $MYSQL_DATABASE
}

# 备份数据库
backup_mysql() {
    log_info "Creating database backup..."
    
    if ! docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
        log_error "MySQL container is not running. Please start it first."
        exit 1
    fi
    
    local backup_file="$BACKUP_DIR/mysql_backup_$(date +%Y%m%d_%H%M%S).sql"
    
    docker exec $CONTAINER_NAME mysqldump -u root -p$MYSQL_ROOT_PASSWORD --all-databases --routines --triggers > "$backup_file"
    
    if [ $? -eq 0 ]; then
        log_success "Database backup created: $backup_file"
    else
        log_error "Database backup failed"
        exit 1
    fi
}

# 恢复数据库
restore_mysql() {
    if [ -z "$1" ]; then
        log_error "Please specify backup file path"
        log_info "Usage: $0 restore <backup_file>"
        exit 1
    fi
    
    local backup_file="$1"
    
    if [ ! -f "$backup_file" ]; then
        log_error "Backup file not found: $backup_file"
        exit 1
    fi
    
    log_info "Restoring database from: $backup_file"
    log_warning "This will overwrite existing data. Continue? (y/N)"
    read -r response
    
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        log_info "Restore cancelled"
        exit 0
    fi
    
    if ! docker ps -q -f name=$CONTAINER_NAME | grep -q .; then
        log_error "MySQL container is not running. Please start it first."
        exit 1
    fi
    
    docker exec -i $CONTAINER_NAME mysql -u root -p$MYSQL_ROOT_PASSWORD < "$backup_file"
    
    if [ $? -eq 0 ]; then
        log_success "Database restored successfully"
    else
        log_error "Database restore failed"
        exit 1
    fi
}

# 清理数据（危险操作）
clean_mysql() {
    log_warning "This will remove all MySQL data and containers. This action cannot be undone!"
    log_warning "Continue? (y/N)"
    read -r response
    
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        log_info "Clean operation cancelled"
        exit 0
    fi
    
    log_info "Stopping and removing MySQL containers..."
    docker-compose -f $COMPOSE_FILE down -v
    
    log_info "Removing data volumes..."
    sudo rm -rf volumes/data/*
    
    log_success "MySQL data cleaned successfully"
}

# 显示帮助信息
show_help() {
    echo "ENPlatform Assistant MySQL Management Script"
    echo ""
    echo "Usage: $0 <command> [options]"
    echo ""
    echo "Commands:"
    echo "  start           Start MySQL service"
    echo "  stop            Stop MySQL service"
    echo "  restart         Restart MySQL service"
    echo "  status          Show service status"
    echo "  logs            Show MySQL logs"
    echo "  connect         Connect to MySQL"
    echo "  backup          Create database backup"
    echo "  restore <file>  Restore database from backup"
    echo "  setup-arch      Setup architecture-specific configuration"
    echo "  verify          Verify deployment and generate report"
    echo "  clean           Clean all data (dangerous)"
    echo "  help            Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 start"
    echo "  $0 backup"
    echo "  $0 restore ./backups/mysql_backup_20231201_120000.sql"
}

# 主函数
main() {
    case "${1:-}" in
        start)
            start_mysql
            ;;
        stop)
            stop_mysql
            ;;
        restart)
            restart_mysql
            ;;
        status)
            status_mysql
            ;;
        logs)
            logs_mysql
            ;;
        connect)
            connect_mysql
            ;;
        backup)
            backup_mysql
            ;;
        restore)
            restore_mysql "$2"
            ;;
        setup-arch)
            setup_architecture
            ;;
        verify)
            if [[ -f "scripts/verify-deployment.sh" ]]; then
                bash scripts/verify-deployment.sh
            else
                log_error "验证脚本不存在"
                exit 1
            fi
            ;;
        clean)
            clean_mysql
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            log_error "Unknown command: ${1:-}"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
